package com.atguigu.flink.chapter06.state.keyed;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2023/6/20 14:23
 */
public class ValueStateDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        // 输出每个传感器的最大水位
        env
            .socketTextStream("hadoop162", 8888)
            .map(new WaterSensorMapFunction())
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
    
                private ValueState<Integer> maxVcState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 在 open 方法中获取需要的键控状态
                    maxVcState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("maxVc", Integer.class));
                }
    
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    Integer currentVc = value.getVc();
                    // 获取状态中的值
                    Integer maxVc = maxVcState.value();
                    /*if (maxVc != null) {
                        if (currentVc > maxVc) {
                            maxVcState.update(currentVc);  // 更新状态
                        }
                    }else{
                        maxVcState.update(currentVc);
                    }*/
                    
                    if(maxVc != null && currentVc > maxVc){
                        maxVc = currentVc;
                    }else if(maxVc == null){
                        maxVc = currentVc;
                    }
                    maxVcState.update(currentVc); // 更新状态中的值
                   
                    out.collect(ctx.getCurrentKey() + " 的最大水位值: " + maxVc);
                    
    
                }
            })
            .print();
            
           
            
        
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
